package com.zgroup.services

class DynamicService {

  boolean transactional = true

  def makeOrderBy(String alias, Map params) {
    def sort = "id"
    def order = ""
    if (params.sort) {
      sort = params.sort
    }
    if (params.order) {
      order = params.order
    }
    return " order by " + alias + "." + sort + " " + order
  }

  def makeOrderBy(Class domain, Map params) {
    return makeOrderBy(domain.getSimpleName().substring(0, 1).toLowerCase(), params)
  }

  def paginateList(String query, Collection positionalParams, Map paginateParams, Class domain) {
    def count = domain.executeQuery("select count(*) as c " + query, positionalParams).getAt(0)
    def items;
    if (count > 0) {
      items = domain.findAll(query + makeOrderBy(domain, paginateParams), positionalParams, paginateParams)
    } else {
      items = []
    }
    [
            "items": items,
            "count": count
    ]
  }

  def paginateList(String query, Map namedParams, Map paginateParams, Class domain) {
    def count = domain.executeQuery("select count(*) as c " + query, namedParams).getAt(0)
    def items;
    if (count > 0) {
      items = domain.findAll(query + makeOrderBy(domain, paginateParams), namedParams, paginateParams)
    } else {
      items = []
    }
    [
            "items": items,
            "count": count
    ]
  }
//    def paginateList(Class domain,String byConditions, Collection positionalParams, Map paginateParams) {
//        [
//            "items":domain."findAllBy$byConditions"(positionalParams,paginateParams),
//            "count":domain."countBy$byConditions"(positionalParams)
//        ]
//    }

  static String escapeLike(String str) {
    StringBuffer bf = new StringBuffer();
    for (int i = 0; i < str.length(); i++) {
      char c = str.charAt(i);
      if (c == '%' || c == '％' || c == '_' || c == '＿' || c == '\\') {
        bf.append('\\');
      }
      bf.append(c);
    }
    return bf.toString();
  }
}
